import { Page } from '@/base/Page';
import { deepAssign } from '@/base/util/Objects';
import { DeviceSort } from '@/base/model/DeviceSort';
import { DeviceModel } from '@/base/model/DeviceModel';
import { Device } from '@/base/model/Device';
import { DevVo } from '@/base/model/DevVo';
import { Agent } from '@/base/model/Agent';
import { Company } from '@/base/model/Company';
import { DeviceUse } from '@/base/model/DeviceUse';
import { DeviceReset } from '@/base/model/DeviceReset';
import { getAgentList } from '@/base/api/AgentApi';
import { getCompany, getCompanyList } from '@/base/api/CompanyApi';
import { calculateTrendLine } from "@/base/util/Dates";
import {
  deteDeviceId,
  getDevice,
  getDeviceId,
  postDevice,
  PutDeviceId,
  PutDeviceBatchAgent,
  PutDeviceBatchDelete,
  PutDeviceBatchSort,
  getErrorExcel,
  getDeviceBatchExcel,
  getDeviceMember
} from '@/base/api/DevcieApi';
import { getDeviceModel, getDeviceModelAll, getDeviceModelId, getDeviceUsage } from '@/base/api/DeviceModelApi';
import { getDeviceSort, getDeviceSortId } from '@/base/api/DeviceSortApi';
import { getDeviceUseList, getDeviceUseModelLifetime, getDeviceUseModeUse, deleteDeviceFault, deleteDeviceUse } from '@/base/api/DeviceUseApi';
import { getDeviceFault } from '@/base/api/DeviceFaultApi';
import { DeviceMemberVo } from '@/base/model/DeviceMemberVo';
import { DeviceFault } from '@/base/model/DeviceFault';
import { firmwareVersions } from '@/base/api/FirmwareApi';
import { getVersions } from '@/base/api/SoftwareApi';
import { SeftMotion } from '@/base/model/SeftMotion';
import { getModelSelfMotionDownloadedByDeviceSn, selectByDeviceId, postSalesRecords, getMaintenanceTips } from '@/base/api/SeftMotionApi';
import { updateMark } from '@/base/api/DeviceModelApi';
import { getDeviceResetList,restoreFactorySettings } from '@/base/api/DeviceResetApi';

export class DevicesBloc {
  page: Page<DeviceSort> = new Page<DeviceSort>([], 0, 1, 15, 0, []);
  page1: Page<DeviceModel> = new Page<DeviceModel>([], 0, 1, 15, 0, []);
  angent: Page<Agent> = new Page<Agent>([], 0, 1, 15, 0, []);
  DevVo: Page<DevVo> = new Page<DevVo>([], 0, 1, 10, 0, []);
  companyList: Page<Company> = new Page<Company>([], 0, 1, 10, 0, []);
  deviceUse: Page<DeviceUse> = new Page<DeviceUse>([], 0, 1, 15, 0, []);
  deviceReset: Page<DeviceReset> = new Page<DeviceReset>([], 0, 1, 15, 0, []);
  model: any = {
    agentId: [],
    city: '',
    cityId: '',
    companyId: 0 || undefined,
    deviceSn: '',
    startImage: '',
    modelId: 0 || undefined,
    modelName: '',
    province: '',
    provinceId: '',
    sortId: 0 || undefined,
    createBegin: 0 || undefined,
    createEnd: 0 || undefined,
    statusCode: '',
    sortDirection: 'DESC'
  };
  deviceResetModel: any = {
    deviceSn: '',
    accountName: ''
  };
  fileList: Array<any> = []
  agentEdit = {
    agentId: 0
  }
  deviceSnAdd = {
    deviceSn: ''
  }
  deviceId: any = {
    id: 0 || undefined,
    deviceSn: '',
    startImage: '',
    statusCode: '',
    modelId: 0 || undefined,
    sortId: 0 || undefined,
    agentId: 0 || undefined,
    modelName: [],
    sortName: [],
    agentName: []
    // startSwitch: '',
    // startTime: '',
    // startType: ''
  };
  sortList: any = [];
  sortListByCompany: any = [];
  modelList: any = [];
  // modelListByCompany: any = [];
  modelListAll: any = [];
  agentList: any = [];
  deviceSn: number[] = [];
  firmwareVersions: any[] = []
  pluginVersions: any[] = []
  excelError: any = {
    normalNum: 0,
    errorNum: 0,
    errorHint: []
  };
  importExcel: any = {
    dispose: '',
    url: ''
  };
  successData: any = '';
  DeviceUse: Page<DeviceUse> = {
    extras: [],
    itemCount: 0,
    items: [],
    pageCount: 0,
    pageSize: 10,
    pageIndex: 1
  };
  ModeLifetimeVo: any = { xAxis: '', yAxis: 0, text: '' };
  ModeUseNumVo: any = { xAxis: '', yAxis: 0, text: '' };

  startValue=0
  endValue=0
  optionsDeviceUsage:object={
      color: ['#2d8cf0', '#91CC75', '#ee656e'],
      title: {
          text: '使用次数统计',
          left: 'center',
          top: 5
      },
      tooltip:{
          trigger: 'axis'
      },
      toolbox: {
          feature: {
          dataView: { show: true, readOnly: false },
          restore: { show: true },
          saveAsImage: { show: true }
          }
      },
      legend: {
          bottom:0,
          data: [ '平均线','数据展示','趋势线']
      },
      grid: [{ left: '5%', top: '10%', width: '90%', height: '80%' }],
      xAxis: [
          {
          name: '日期',
          type: 'category',
          boundaryGap: false,
          }
      ],
      yAxis: {
          name: '次数',
          type: 'value'
      },
      series: [
          {
              name: '平均线',
              type: 'line',
              data: []
          },
          {
              name: '数据展示',
              type: 'line',
              data: []
          },
          {
              name: '趋势线',
              type: 'line',
              markLine: {
                  animation: true,
                  lineStyle: {
                  type: 'dashed',
                  color: 'red'
                  },
                  data: [
                  [
                      {
                      coord: [0, 0],
                      symbol: 'none'
                      },
                      {
                      coord: [0, 0],
                      symbol: 'none'
                      }
                  ]
                  ]
              }
          },
      ]
  }
  dateDeviceUsage = [
    new Date(new Date().getTime()-6*30*24*60*60*1000),
    new Date()
  ]

  loading = false;

  load(model) {
    this.loading = true;
    let that = this;
    return getDeviceModelAll({ companyId: model.companyId }).then((res) => {
      this.sortListByCompany = res.data.map(function (item: any) {
        let obj = { id: 0, sortName: '' };
        obj.id = item.id;
        obj.sortName = item.sortName;
        return obj
      });
      return res;
    }).finally(() => {
      this.loading = false;
    })
  }

  getAllAngent(pageIndex: number, pageSize: number, sortDirection: string) {
    this.loading = true;
    return getAgentList({
      pageIndex,
      pageSize,
      companyId: this.model.companyId
    }).then((res) => {
      deepAssign(this.angent, res.data);
      this.agentList = this.angent.items.map(function (item) {
        let obj = { id: 0, agentName: '' };
        obj.id = item.id;
        obj.agentName = item.agentName;
        return obj;
      });
      return this.agentList;
    }).finally(() => {
      this.loading = false;
    });
  }
  removeUseItem(dateItem: DeviceUse) {
    this.loading = true;
    return deleteDeviceUse(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }
  removeFaultItem(dateItem: DeviceUse) {
    this.loading = true;
    return deleteDeviceFault(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }
  getAllSort(pageIndex: number, pageSize: number, sortDirection: string) {
    this.loading = true;
    let that = this;
    return getDeviceSort({
      pageIndex,
      pageSize,
      sortDirection
    }).then((res) => {
      deepAssign(this.page, res.data);
      this.sortList = this.page.items.map(function (item) {
        var obj = { id: 0, sortName: '' };
        // @ts-ignore
        obj.id = item.id;
        obj.sortName = item.sortName;
        return obj;
      });
      return this.sortList;
    }).finally(() => {
      this.loading = false;
    });
  }

  getSortName(id) {
    let item = this.sortList.find(item => item.id === id);
    return item == null ? '' : item.sortName;
  }

  getAllModel(pageIndex: number, pageSize: number, sortId, sortDirection: string, companyId) {
    this.loading = true;
    let that = this;
    console.log(companyId)
    return getDeviceModel({
      pageIndex,
      pageSize,
      sortId,
      sortDirection,
      companyId,
      id: this.model.id,
      modelName: this.model.modeName
    }).then((res) => {
      deepAssign(this.page1, res.data);
      this.modelList = this.page1.items.map(function (item) {
        var obj = { id: 0, modelName: '' };
        obj.id = item.id;
        obj.modelName = item.modelName;
        return obj;
      });
      return this.modelList;
    }).finally(() => {
      this.loading = false;
    });
  }

  getfirmware() {
    return firmwareVersions({ modelId: this.model.modelId }).then((res) => {
      this.firmwareVersions = res.data
    }).finally(() => {
      this.loading = false;
    })
  }

  getPlugin() {
    return getVersions({ modelId: this.model.modelId }).then((res) => {
      this.pluginVersions = res.data
    }).finally(() => {
      this.loading = false;
    })
  }

  getModelName(id) {
    let item = this.modelListAll.find(item => item.id === id);
    return item == null ? '' : item.modelName;
  }

  company = new Company();

  getCompanyList(pageIndex: number,
    pageSize: number,
    sortDirection: string) {
    return getCompanyList({ pageIndex, pageSize, sortDirection, name: '', createBegin: '' })
      .then((res) => {
        this.companyList = res.data;
        return res;
      }).finally(() => {
        this.loading = false;
      });
  }

  getCompanyName(id) {
    let item = this.companyList.items.find(item => item.id === id);
    return item == null ? '' : item.name;
  }

  getCompany(id: number) {
    return getCompany(id)
      .then((res) => {
        let dataItem = res.data.company;
        this.company.id = dataItem.id;
        this.company.name = dataItem.name;
        this.company.shortName = dataItem.shortName;
        this.company.phone = dataItem.phone;
        this.company.clientUrl = dataItem.clientUrl;
        this.company.address = dataItem.address;
      });
  }

  sort = new DeviceSort();

  getDeviceSortId(id: number) {
    return getDeviceSortId(id)
      .then((res) => {
        deepAssign(this.sort, res.data);
        return res;
      });
  }

  addDevice(
    deviceSn: string,
    modelId: number,
    sortId: number) {
    this.loading = true;
    return postDevice({
      deviceSn, modelId, sortId
    }).then((res) => {
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  getDevice(
    pageIndex: number, pageSize: number, sortDirection: string, model?: any) {
    this.loading = true;
    return getDevice({
      pageIndex: pageIndex,
      pageSize: pageSize,
      sortDirection: sortDirection,
      agentId: this.model.agentId,
      cityId: this.model.cityId,
      companyId: this.model.companyId,
      createBegin: this.model.createBegin,
      createEnd: this.model.createEnd,
      deviceSn: this.model.deviceSn,
      modelId: this.model.modelId,
      modelName: this.model.modelName,
      provinceId: this.model.provinceId,
      sortId: this.model.sortId,
      statusCode: this.model.statusCode
    }).then((res) => {
      this.DevVo = res.data;
      this.DevVo.items.forEach(item => {
        this.DevVo.extras.forEach(extra => {
          if (extra.id === item.agentid) {
            item.agentName = extra.agentName;
          }
        });
      });
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  getModel(id: number) {
    this.loading = true;
    return getDeviceModelId({ id }).then((res) => {
      deepAssign(this.model, res.data);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  toModifyItem(id: number) {
    this.loading = true;
    return getDeviceId(
      id
    ).then((res) => {
      deepAssign(this.deviceId, res.data);
      return this.deviceId;
    }).finally(() => {
      this.loading = false;
    });
  }

  modifyItem(id: number, deviceSn: string) {
    this.loading = true;
    return PutDeviceId({
      sortId: this.deviceId.sortId,
      modelId: this.deviceId.modelId,
      startImage: this.deviceId.startImage,
      id,
      deviceSn
    }).then((res) => {
      deepAssign(this.deviceId, res.data);
      this.getDevice(this.DevVo.pageIndex, 10, 'DESC', this.model);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: Device) {
    this.loading = true;
    return deteDeviceId(dateItem.id)
      .then((res) => {
        this.getDevice(this.DevVo.pageIndex, 10, 'DESC', this.model);
        return res;
      })
      .finally(() => {
        this.loading = false;
      });
  }

  PutDeviceBatchAgent(agentId: number, deviceSn: object) {
    this.loading = true;
    return PutDeviceBatchAgent({
      agentId,
      deviceSn
    }).then((res) => {
      this.getDevice(this.DevVo.pageIndex, 10, 'DESC', this.model);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  PutDeviceBatchDelete(deviceSn: object) {
    this.loading = true;
    return PutDeviceBatchDelete({
      deviceSn
    }).then((res) => {
      this.getDevice(this.DevVo.pageIndex, 10, 'DESC', this.model);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  PutDeviceBatchSort(deviceSn: number[], modelId: number, sortId: number) {
    this.loading = true;
    return PutDeviceBatchSort({
      deviceSn,
      modelId,
      sortId
    }).then((res) => {
      this.getDevice(this.DevVo.pageIndex, 10, 'DESC', this.model);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  getErrorExcel(url: string) {
    this.loading = true;
    if (url === '') {
      return false;
    }
    return getErrorExcel({ url }).then((res) => {
      deepAssign(this.excelError, res.data);
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  getDeviceBatchExcel(url: string) {
    this.loading = true;
    if (url === '') {
      return false;
    }
    return getDeviceBatchExcel({ dispose: 'COVER', url }).then((res) => {
      this.successData = res.data;
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  getDeviceUse(pageIndex, pageSize, sortDirection, companyId, deviceId) {
    return getDeviceUseList({
      pageIndex,
      pageSize,
      sortDirection,
      companyId,
      deviceId
    }).then(res => {
      deepAssign(this.deviceUse, res.data);
      return res;
    }).finally(() => {

    });
  }

  getDeviceResetList(
    pageIndex: number, pageSize: number, sortDirection: string, deviceResetModel?: any) {
    return getDeviceResetList({
      pageIndex: pageIndex,
      pageSize: pageSize,
      sortDirection: sortDirection,
      deviceSn: this.deviceResetModel.deviceSn,
      accountName: this.deviceResetModel.accountName
    }).then((res) => {
      this.deviceReset = res.data;
      return res;
    });
  }

  restoreFactorySettings(id: number) {
    return restoreFactorySettings(id)
  }

  getDeviceUseModelLifetime(deviceId, companyId) {
    return getDeviceUseModelLifetime({ deviceId, companyId }).then(res => {
      this.ModeLifetimeVo.text = '模式使用时长';
      this.ModeLifetimeVo.xAxis = res.data.map(item => {
        return item.modename;
      });
      this.ModeLifetimeVo.yAxis = res.data.map(item => {
        return Math.ceil(item.lifetime/60);
      });
      // deepAssign(this.ModeLifetimeVo, res.data);
    }).finally(() => {

    });
  }

  getDeviceUseModeUse(deviceId, companyId) {
    return getDeviceUseModeUse({ deviceId, companyId }).then(res => {
      this.ModeUseNumVo.text = '模式使用次数';
      this.ModeUseNumVo.xAxis = res.data.map(item => {
        return item.modename;
      });
      this.ModeUseNumVo.yAxis = res.data.map(item => {
        return item.num;
      });
      return this.ModeUseNumVo;
    }).finally(() => {

    });
  }

  DeviceMemberVo = new DeviceMemberVo();

  getDeviceMember(id) {
    return getDeviceMember({
      id
    }).then(res => {
      return res.data;
    }).finally(() => {

    });
  }

  DeviceFault: Page<DeviceFault> = new Page<DeviceFault>([], 0, 1, 10, 0, []);

  getDeviceFault(pageIndex, pageSize, sortDirection, deviceId) {
    return getDeviceFault({
      pageIndex,
      pageSize,
      sortDirection,
      deviceId
    }).then(res => {
      deepAssign(this.DeviceFault, res.data);
      return res;
    }).finally(() => {

    });
  }

  SeftMotion: Array<SeftMotion> = [];

  getModelSelfMotionDownloadedByDeviceSn(deviceSn:string) {
    return getModelSelfMotionDownloadedByDeviceSn(
      deviceSn
    ).then(res => {
      this.SeftMotion = res.data
      // deepAssign(this.SeftMotion, res.data);
      return res;
    }).finally(() => {

    });
  }

  selectByDeviceId(deviceId:number) {
    return selectByDeviceId(
      deviceId
    ).then(res => {
      return res;
    }).finally(() => {

    });
  }
  getMaintenanceTips(deviceSn:String) {
    return getMaintenanceTips(
      deviceSn
    ).then(res => {
      return res;
    }).finally(() => {

    });
  }
  postSalesRecords(data){
    return postSalesRecords(
      data
    ).then(res => {
      return res;
    }).finally(() => {

    });
  }

  updateMark(deviceId:number,id:number){
    return updateMark({
      deviceId,
      id
    }).then(res => {

    })
  }

  async getDeviceUsage(){
    let startTime:any=this.dateDeviceUsage[0].getTime()
    let endTime:any=this.dateDeviceUsage[1].getTime()
    return await getDeviceUsage({
        startTime,
        endTime,
        deviceSn:this.deviceId.deviceSn
    }).then((res)=>{
        // console.log(res.data);return;
        if(res.data.length<=0)return
        const dataList:any=[]
        const dataAvg:any=[]
        // 1. 提取num字段为一个数组
        const nums = res.data.map(item => item.num);
        // 2. 求和
        const sum = nums.reduce((total, cur) => total + cur, 0);
        // 3. 求平均值
        const avg = Math.ceil(sum / nums.length);
        res.data.map((item)=>{
            dataList.push([item.month,item.num])
            dataAvg.push([item.month,avg])
        })
        const trendLine=calculateTrendLine(res.data)
        // console.log('斜率:', trendLine.slope);
        // console.log('截距:', trendLine.intercept);
        // console.log('起始点值:', trendLine.startValue);
        // console.log('结束点值:', trendLine.endValue);
        this.startValue=trendLine.startValue
        this.endValue=trendLine.endValue
        this.optionsDeviceUsage['series'][0]['data']=dataAvg
        this.optionsDeviceUsage['series'][1]['data']=dataList
        this.optionsDeviceUsage['series'][2]['markLine']['data'][0][0]['coord'][0]=dataList[0][0]
        this.optionsDeviceUsage['series'][2]['markLine']['data'][0][0]['coord'][1]=this.startValue
        this.optionsDeviceUsage['series'][2]['markLine']['data'][0][1]['coord'][0]=dataList[dataList.length-1][0]
        this.optionsDeviceUsage['series'][2]['markLine']['data'][0][1]['coord'][1]=this.endValue
        // console.log(dataList,trendLine,this.optionsDeviceUsage)
    })
}



}
